const { BASE_URL, SUCCESS_CODE, LOGIN_EXCEPTION_CODE, SPECIAL_BUSINESS_CODE } = require('@/config/index.js')

// 全局Loading效果
let TOTAL_LOADING = false
let PENDING_LIST = []

const http = {
  get(url, data, opt) {
    return this.ajax('GET', url, data, opt)
  },
  post(url, data, opt) {
    return this.ajax('POST', url, data, opt)
  },
  put(url, data, opt) {
    return this.ajax('PUT', url, data, opt)
  },
  delete(url, data, opt) {
    return this.ajax('DELETE', url, data, opt)
  },
  ajax(method, url, data, opt) {
    const loading = opt?.cancelLoading === true ? false : true
    const timestamp = Date.now() + Math.random().toString().substr(2, 2)
    PENDING_LIST.push({
      timestamp,
      url,
      loading
    })
    return new Promise((resolve, reject) => {
      if (PENDING_LIST.some(v => v.loading) && !TOTAL_LOADING) {
        TOTAL_LOADING = true
        uni.showLoading({
          title: opt?.loadingText || '拼命加载中',
          mask: true
        })
      }
      uni.request({
        url: `${BASE_URL}${url}`,
        method,
        data,
        header: {
          'Content-Type': opt?.submitType === 'json' ? 'application/json' : 'application/x-www-form-urlencoded',
          'token': uni.getStorageSync('token') || ''
        },
        success(res) {
          PENDING_LIST.map(v => {
            if (v.url === url && v.timestamp === timestamp) {
              v.loading = false
            }
            return v
          })
          if (PENDING_LIST.every(v => !v.loading) && TOTAL_LOADING) {
            PENDING_LIST = []
            TOTAL_LOADING = false
            uni.hideLoading()
          }
          if (res.statusCode !== 200) {
            uni.showToast({
              icon: 'none',
              title: '服务器连接失败'
            })
            reject({ errMsg: '服务器连接失败' })
            return
          }
          const { code, msg } = res.data;
          if (SUCCESS_CODE.includes(code)) {
            // 成功
            resolve(res.data)
          } else if (LOGIN_EXCEPTION_CODE.includes(code)) {
            // 登录异常
            uni.showModal({
              title: '提示',
              content: msg,
              showCancel: false,
              confirmText: '我知道了',
              success(res) {
                if (res.confirm) {
                  // 清除缓存并跳转登录页
                  uni.clearStorageSync()
                  uni.reLaunch({
                    url: '/subpages/login/index/index'
                  })
                }
              }
            })
          } else if (SPECIAL_BUSINESS_CODE.includes(code)) {
            // 特殊业务逻辑错误码
            resolve(res.data)
          } else {
            // 错误
            uni.showToast({
              icon: 'none',
              title: msg
            })
            reject({ errMsg: msg })
          }
        },
        fail(err) {
          PENDING_LIST.map(v => {
            if (v.url === url && v.timestamp === timestamp) {
              v.loading = false
            }
            return v
          })
          if (PENDING_LIST.every(v => !v.loading) && TOTAL_LOADING) {
            PENDING_LIST = []
            TOTAL_LOADING = false
            uni.hideLoading()
          }
          uni.showToast({
            icon: 'none',
            title: err.errMsg
          })
          reject({ errMsg: err.errMsg })
        }
      })
    })
  }
}

module.exports = http